/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-09-23 16:55:14
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2024-10-18 15:33:38
 * @FilePath: /react18-vite-admin/src/service/useRoutesAndMenus.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { createBrowserRouter, Outlet } from 'react-router-dom';
import { UserOutlined } from '@ant-design/icons';

import {
    type MenuTreeItem,
    type MenuTreeWithMetaItem
} from '@/typings/store/permission';
import { usePermissionStore } from '@/store';
import { treeToArray, arrayToTree } from '@/utils';
import { createReactRouterObjects, constantRoutes, authRoutes } from '@/router';
import BeforeEach from '@/router/BeforeEach';
import { resetInterceptorsNeedSet } from '@/service/app/useRequest';

export const filterAsyncRoutes = (
    menuTree: MenuTreeItem[],
    routes: AppRouteRecordRaw[]
) => {
    const flatArr = treeToArray<MenuTreeItem>(
        JSON.parse(JSON.stringify(menuTree))
    );
    const routeFlatArr = treeToArray<AppRouteRecordRaw>(routes);
    const menuTreeWithMeta: MenuTreeWithMetaItem[] = [];
    flatArr.forEach((menu) => {
        const route = routeFlatArr.find((it) => {
            return it.path === menu.path;
        });
        // 处理路由列表
        if (route) {
            route.meta.title = menu.name;
            menuTreeWithMeta.push(
                Object.assign(menu, {
                    meta: route.meta,
                    name: route.name
                })
            );
        } else {
            menuTreeWithMeta.push(
                Object.assign(menu, {
                    meta: {
                        name: menu.name,
                        title: menu.name,
                        path: '',
                        fullPath: '',
                        icon: <UserOutlined />
                    },
                    name: undefined
                })
            );
        }
    });
    return {
        menus: arrayToTree<MenuTreeWithMetaItem>(
            menuTreeWithMeta
        ) as MenuTreeWithMetaItem[],
        routes: arrayToTree<AppRouteRecordRaw>(
            routeFlatArr
        ) as AppRouteRecordRaw[]
    };
};

export const useRoutesAndMenus = () => {
    // const { setMenuTree } = useUserStore((state) => state);
    const {
        setReactRouter,
        setRoutes,
        setAddRoutes,
        setNeedUpdate,
        setMenuTree
    } = usePermissionStore((state) => state);

    const resetRouter = () => {
        setReactRouter(undefined);
    };

    const updateRouterAndMenus = (menuTree: MenuTreeItem[]) => {
        if (menuTree.length === 0)
            throw new Error('无效menuTree,menuTree长度不能为0');
        const { routes, menus } = filterAsyncRoutes(menuTree, authRoutes);
        const allRoutes = [...constantRoutes, ...routes];
        resetInterceptorsNeedSet();
        setMenuTree(menus);
        setRoutes(allRoutes);
        setAddRoutes(routes);
        setReactRouter(
            createBrowserRouter(
                [
                    {
                        path: '/',
                        element: (
                            <BeforeEach>
                                <Outlet />
                            </BeforeEach>
                        ),
                        children: createReactRouterObjects(allRoutes)
                    }
                ],
                {
                    basename:
                        import.meta.env.MODE === 'development' ? '/admin' : './'
                }
            )
        );

        setNeedUpdate(false);
        return {
            allRoutes
        };
    };

    return {
        resetRouter,
        updateRouterAndMenus
    };
};
